#-*-coding:utf-8-*-
import os
from bs4 import BeautifulSoup


class getAllElementAtt():
    def getHtml(self,sourcefile,projectpathname,filename):
        '''
        根据传入的文件源代码，项目路径名/文件名，来保存源文件代码
        :param sourcefile:文件源代码
        :param projectpathname:项目路径名
        :param filename:文件名
        :return:
        '''
        f = open(os.path.abspath(os.path.join(os.path.dirname(__file__), "..")) + "//"+projectpathname+'//Resource//'+filename+'.html', 'a+',encoding= 'utf-8')
        f.write(sourcefile)
        f.close()
    def getAllElement(self,sourcename,targetName,projectPath):
        '''
        根据您传入的读取文件名、和目标文件名
         将元素原样存在指定文件中
        :param sourcename:源文件名
        :param targetName:目标文件名
        :return:
        '''
        sourcename = os.path.abspath(
            os.path.join(os.path.dirname(__file__), "..")) + "//"+projectPath+'//Resource//' + sourcename + '.html'
        #soup=BeautifulSoup(open(sourcename,encoding= 'utf-8'),from_encoding = 'utf-8')
        soup = BeautifulSoup(open(sourcename,encoding= 'utf-8'),features="lxml")
        attsFilePath = os.path.abspath(os.path.join(os.path.dirname(__file__), "..")) + "//"+projectPath+ '//Resource//'+targetName+'.py'
        isContuineWrite=True
        if (os.path.exists(attsFilePath)):
            print("==========================准备开始了==================")
            isContuineStr = input("文件已经存在是否重写？Y/N")
            if isContuineStr != "Y":
                isContuineWrite = False
            else:
                os.remove(attsFilePath)
        if isContuineWrite:
            f = open(attsFilePath, 'a+',encoding='utf-8')
            f.write(
                "# encoding=utf-8" + "\n" )
            isContinue=True
            for child in soup.descendants:
                print("=======打印子标签=======")
                print(child)
                des = input("请输入注释信息: ")

                #输入exit结束
                if  des=='exit':
                    isContinue=False
                    break
                elif des != '' and des!='exit':
                    try:

                        print(child.attrs)
                        atts=child.attrs
                    except Exception as e:
                        atts = '\''+str(child)+'\''

                    name = input("请输入命名: \n")
                    f.write("#" + des + "\n")
                    f.write(name + "=" + str(atts) + "\n")
                    childName = child.name
                    attname = input("请输入需要录入的属性，多属性以英文‘,’分割: \n")
                    atts=attname.split(',')
                    xpathInfo=name+"_xpath" + "=\""+'//'+childName
                    for i in range(atts.__len__()):
                        try:
                            print(atts[i])
                            print(child[atts[i]])
                            #driver.find_element_by_xpath('//div[@id="opercode_chosen"]').click()
                            realAtt=''

                            islist=isinstance(child[atts[i]],list)
                            if islist:
                                for z in child[atts[i]]:
                                    realAtt+=(z+' ')
                                realAtt=realAtt.strip()
                            else:
                                realAtt=child[atts[i]]
                            if i==0:
                                xpathInfo+='[@'+atts[i]+"=\'"+realAtt + "\'"
                            else:
                                xpathInfo += " and @" + atts[i] + "=\'" + realAtt + "\'"
                        except  Exception as e:
                            print("不存在该属性值")
                            iscon=input('程序已经出现了异常，是否继续？Y/N\n')
                            if iscon=='Y':
                                continue
                            else:
                                raise e
                    xpathInfo += "]\"" + "\n"
                    f.write(xpathInfo)

if __name__=='__main__':
    # 命名规范 lbt_welcome_mainpage_mainbutton
    # 项目名_模块名_页面名_对象及类型
    getAllElementAtt=getAllElementAtt()
    getAllElementAtt.getAllElement("welcome","WelcomeAtt",'LBT')